import { isNotEmpty3 } from "./validate";
/**
 * 将对象转换为url编码的字符串时，只能使用一层嵌套对象
 *
 * @param params: object to convert
 * @returns: an URL-encoded string
 */
export const tansParams = (params: any): string => {
  let result = '';
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    const part = encodeURIComponent(propName) + '=';
    if (isNotEmpty3(value)) {
      // nested object (only one layer)
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (isNotEmpty3(value[key])) {
            const params = propName + '[' + key + ']';
            const subPart = encodeURIComponent(params) + '=';
            result += subPart + encodeURIComponent(value[key]) + '&';
          }
        }
      } else {  // primitives
        result += part + encodeURIComponent(value) + '&';
      }
    }
  }
  return result;
};